import os 
import time
import sys
import subprocess
import re

cur_dir=os.path.dirname(__file__)
# print(cur_dir)
ls = os.listdir(cur_dir)
dirs = [] 

for ele in ls:
    if len(ele)>0 and ele[0] not in ["d","D","."] and ele!="common":
        ele = os.path.join(cur_dir,ele)
        if os.path.isdir(ele):
            dirs.append(ele)


log_file = os.path.join(cur_dir,"log.txt")
# with open(log_file,"w",encoding="utf-8") as fw:
#     pass

def exec_cmd(cmd):
    args = cmd.split()
    with open(log_file,"a+",encoding="utf-8") as fa:
        p = subprocess.Popen(args, stdout=subprocess.PIPE,stdin=sys.stdin, bufsize=1)
        for line in iter(p.stdout.readline, b''):
            line = line.decode("utf-8").strip()
            print(line)
            fa.write(line+"\n")
        p.stdout.close()
        p.wait()

pattern=re.compile("test_\d+.py")
for d in dirs:
    py_ls = os.listdir(d)
    for py in py_ls:
        # if py != "main_test.py":
        #     continue
        if not pattern.match(py):
            continue
        print()
        try:
            py = os.path.join(cur_dir,d,py)
            print("py_file: [{}]".format(py))
            cmd = "python -u {py}".format(py=py)
            exec_cmd(cmd)
            time.sleep(10)
        except:
            cmd = "echo 未知错误"
            exec_cmd(cmd)
            time.sleep(1)
            continue

print("OVER")
